package com.project.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.net.URLEncoder;

/**
 * @Description: 发送验证码
 * @Author: zhuchi
 * @CreateDate: 2020/6/21 20:46
 * @Version: 1.0
 */
@Slf4j
public class SendCodeUtil {

    /**
     * 发送验证码短信（国际短信）
     * @param mobile
     * @param code
     * @throws Exception
     */
    public static int sendsms(String mobile, String code){
        HttpClient httpClient = new HttpClient();
        //普通短信 http://api.1cloudsp.com/api/v2/single_send
        PostMethod postMethod = new PostMethod("http://intlapi.1cloudsp.com/intl/api/v2/send");
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

        String accesskey = "0yp5xAAoDrwAnuuA"; //用户开发key
        String accessSecret = "RHGE82AyH1cMEghj0vPgDuGuPEDQ8Pon"; //用户开发秘钥

        try {
            NameValuePair[] data = {
                    new NameValuePair("accesskey", accesskey),
                    new NameValuePair("secret", accessSecret),
                    new NameValuePair("sign", "【GoIns】"),
                    new NameValuePair("templateId", "3605"),
                    new NameValuePair("mobile", mobile),
                    new NameValuePair("content", URLEncoder.encode(code, "utf-8"))
            };
            postMethod.setRequestBody(data);
            postMethod.setRequestHeader("Connection", "close");

            int statusCode = httpClient.executeMethod(postMethod);
            System.out.println("statusCode: " + statusCode + ", body: " + postMethod.getResponseBodyAsString());

            return statusCode;
        }catch (Exception e){
            e.printStackTrace();
            log.info("为" + mobile + "发送验证码时发生异常");
        }

        return 500;
    }

    public static void main(String[] args) throws Exception {
        SendCodeUtil t = new SendCodeUtil();
        //普通短信
        t.sendsms("60176628670", "123456");
    }

}
